var APP_ENV_DEV = false // true 开发环境， false 生产环境
// 接口相关方法
var apiUtil = (function(){

    // 获取url中query中某个key对应的值
    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substring(1).match(reg);
        if (r != null) {
        return decodeURIComponent(r[2])
        }
        return null;
    }
    
    // 通用Ajax方法
    function ajaxRequest(options) {
        return new Promise((resolve, reject) => {
            // 默认配置
            const defaultOptions = {
                url: '',
                type: 'GET',
                dataType: 'json',
                data: null,
                timeout: 10000
            };
            if(options.type.toLocaleUpperCase() === 'GET') {
                defaultOptions.contentType = 'application/json;charset=utf-8'
            } else if (options.type.toLocaleUpperCase() === 'POST') {
                defaultOptions.contentType = 'application/x-www-form-urlencoded;charset=utf-8'
            } else { }
            
            // 合并配置
            const config = { ...defaultOptions, ...options }
            
            // 发送请求
            $.ajax({
                url: config.url,
                type: config.type,
                contentType: config.contentType,
                dataType: config.dataType,
                data: config.data || null,// config.data ? JSON.stringify(config.data) : null,
                timeout: config.timeout,
                success: function(response) {
                    resolve(response)
                },
                error: function(xhr, status, error) {
                    reject({ xhr, status, error })
                }
            })
        })
    }

    // 接口：获取全部流程json数据
    function getAllProcessData() {
        return new Promise((resolve,reject)=>{
            let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testProcessInfo.json',
                    type: 'get',
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_GET_FLOW_DATA",
                        materialUUID: materialUUID, // 物料唯一标识
                        craftPathUUID: craftPathUUID, // 路线唯一标识
                        bindID: bindID // 模型数据结构唯一标识
                    },
                }
            }

            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }

    // 接口：获取工作项目列表 (子阶段)
    function getProjectData(baseInfo) {
        console.log("getProjectData:", baseInfo)
        return new Promise((resolve,reject)=>{
            let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testProjectData.json',
                    type: 'get',
                    data: {
                        baseInfo: JSON.stringify(baseInfo)
                    }
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_GET_PROJECT_DATA",
                        baseInfo: JSON.stringify(baseInfo)
                    }
                }
            }

            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }
    // 接口：获取工作要素列表 (活动节点)
    function getElementData(baseInfo, projectData) {
        return new Promise((resolve,reject)=>{
            let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testElementData.json',
                    type: 'get',
                    data: {
                        baseInfo: JSON.stringify(baseInfo),
                        projectData: JSON.stringify(projectData)
                    }
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_GET_ELEMENT_DATA",
                        baseInfo: JSON.stringify(baseInfo),
                        projectData: JSON.stringify(projectData)  
                    }
                }
            }

            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }

    // 接口：保存流程数据
    function saveProcessInfoData(baseInfo, processData) {
        return new Promise((resolve,reject)=>{
             let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testSaveProcessInfo.json',
                    type: 'get',
                    data: {
                        baseInfo,
                        processData
                    }
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_XXX",
                        baseInfo,
                        processData
                    }
                }
            }
            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }
    // 接口：拖拽工作项目节点后保存
    function saveDragProject(baseInfo, paramJson) {
        return new Promise((resolve,reject)=>{
             let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testSaveProcessInfo.json',
                    type: 'get',
                    data: {
                        baseInfo: JSON.stringify(baseInfo),
                        paramJson
                    }
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_XXX",
                        baseInfo: JSON.stringify(baseInfo),
                        paramJson
                    }
                }
            }
            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }
    // 接口：拖拽工作要素节点后保存
    function saveDragELement(baseInfo, paramJson) {
        return new Promise((resolve,reject)=>{
             let params = null
            if(APP_ENV_DEV) {
                // 开发环境 测试mock
                params = {
                    url: './mock/testSaveProcessInfo.json',
                    type: 'get',
                    data: {
                        baseInfo: JSON.stringify(baseInfo),
                        paramJson
                    }
                }
            } else {
                // 生产环境 后端接口
                params = {
                    type: "post",
                    url: "./jd?",
                    data: {
                        sid: sid,
                        cmd: "com.awspaas.user.apps.model_XXX",
                        baseInfo: JSON.stringify(baseInfo),
                        paramJson
                    }
                }
            }
            ajaxRequest(params).then((res)=>{
                resolve(res)
            }).catch((error)=> reject(error))
        })
    }

    return {
        getQueryString,
        getAllProcessData,
        getProjectData,
        getElementData,
        saveProcessInfoData,
        saveDragProject,
        saveDragELement
    }
})()

// 通用工具方法
var commonUtil = (function(){

    /**
     * 确认弹框
     * 使用范例：commonUtil.showConfirm({
     *              message: '是否关闭?',
     *              onConfirm: function() { // 确定时 },
     *              onCancel: function() { // 取消时 }
     *          })     
     * @param {*} options 
     * @returns 
     */
    function showConfirm(options) {
        // 默认选项
        const defaults = {
            title: '提示',
            width: 400,
            message: '您确定要执行此操作吗？',
            confirmText: '确定',
            cancelText: '取消',
            onConfirm: function() {},
            onCancel: function() {}
        }
        // 合并选项
        const settings = $.extend({}, defaults, options)
        
        // 创建对话框内容
        const dialogContent = $('<div></div>')
            .html('<p>' + settings.message + '</p>')
        
        // 创建并显示对话框
        dialogContent.dialog({
            title: settings.title,
            modal: false,
            width: settings.width,
            classes: {
                "ui-dialog": "confirm-dialog", // 弹窗css
                "ui-dialog-titlebar": "confirm-dialog-titlebar"
            },
            buttons: [
                {
                    text: settings.confirmText,
                    click: function() {
                        $(this).dialog('close')
                        settings.onConfirm()
                    }
                },
                {
                    text: settings.cancelText,
                    click: function() {
                        $(this).dialog('close')
                        settings.onCancel()
                    }
                }
            ],
            close: function() {
                $(this).dialog('destroy').remove()
            }
        })
    }

    return {
        showConfirm
    }
})()